<template lang="pug">
  .login-body
    h4 登录
    Form(ref='loginForm',:model='formValidate',:rules='ruleValidate')
      FormItem(prop='username')
        Input(v-model="formValidate.username",icon='md-contacts',placeholder='用户名')
      FormItem(prop='passwd')
        Input(v-model="formValidate.passwd",type='password',icon='ios-lock-outline',placeholder='密码',@keyup.enter.native='handleSubmit')
    Button(type='primary',long,:loading="loading",@click='handleSubmit').login-submitBtn
      span {{!loading ? '登录' : '登录中...'}}
</template>

<script>
import asyncLogin from '../api'

export default {
  data() {
    return {
      loading: false,
      formValidate: {
        username: '',
        passwd: ''
      },
      ruleValidate: {
        username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
        passwd: [{ required: true, message: '请输入密码', trigger: 'blur' }]
      }
    }
  },
  methods: {
    handleSubmit() {
      this.$refs['loginForm'].validate(async valid => {
        if (valid) {
          try {
            this.loading = true
            const res = await asyncLogin.login({ data: { loginName: this.formValidate.username, pwd: this.$md5(this.formValidate.passwd) } })
            this.handleRouter()
            this.$cookie.set('token', res.data.data.token)
            sessionStorage.setItem('username', res.data.data.userName)
            sessionStorage.setItem('userId', res.data.data.userId)
            this.loading = false
          } catch (error) {
            this.loading = false
          }
        }
      })
    },
    handleRouter: async function() {
      try {
        const menuData = await asyncLogin.getUserRight({ data: {} })
        this.$store.dispatch('menu/transRouter', menuData.data.data)
        sessionStorage.setItem('routes', JSON.stringify(menuData.data.data))
        if (menuData.data.data[0].path === '') {
          this.$router.push(`${menuData.data.data[0].children[0].path}`)
        } else {
          this.$router.push(`${menuData.data.data[0].path}/${menuData.data.data[0].children[0].path}`)
        }
      } catch (error) {}
    }
  }
}
</script>
